import React from 'react';
import _ from 'underscore';

import { Scope } from 'lib/scopeFactory';

import { defaultApi } from '../../apis/core-util';

import EventEditor from './EventEditor.jsx';

export default class MainScope extends Scope {
  constructor(props, context) {
    super(props, context);
    this.$state = {
      loading: true,
      keyword: '',
      events: [],

      grid: {
        loading: true
      }
    }; // $state

    this.$state.gridCols = [
      {
        title: '虚拟事件名',
        sortable: true,
        key: 'name',
        render: (cellValue, rowData) => (
          <a
            href="javascript:;"
            onClick={ this.showEditor.bind(this, rowData) }>
            { cellValue }
          </a>
        )
      },
      {
        title: '事件中文名称',
        sortable: true,
        key: 'cname'
      },
      {
        title: '包含事件',
        key: 'virtual_define',
        render: cellValue => {
          return (
            <span>{ cellValue.map(item => item.event_name).join(', ') }</span>
          );
        }
      },
      {
        title: '编辑',
        key: 'editor',
        render: (cellValue, rowData) => (
          <a
            href="javascript:;"
            className="iconfont"
            onClick={ this.showEditor.bind(this, rowData) }>
            &#xe637;
          </a>
        )
      }
    ]; // gridCols

    this.gridApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/events/virtual`
    });
  } // constructor

  showEditor(item) {
    EventEditor.mount({
      item,
      onClose: success => {
        if (success === true) {
          this.fetch();
        }
      }
    });
  } // showEditor

  fetch() {
    this.gridApi
        .fetch()
        .progress(() => {
          this.$state.grid = {
            loading: true
          };
          this.emit();
        })
        .fail(error => this.$state.grid = { error })
        .done(data => this.$state.grid = {
          data,
          _data: data
        })
        .always(() => this.emit());
  }

  $search_keyword(payload) {
    if (this.$state.grid._data) {
      this.$state.grid.data = _.chain(this.$state.grid._data)
                               .filter(item => item.name.toLowerCase().indexOf(payload.value) >= 0 ||
                                               item.cname.toLowerCase().indexOf(payload.value) >= 0)
                               .value();
      this.emit();
    }
  }

  $load() {
    this.fetch();
  }
}
